<script setup>
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import protobufjson from '@renderer/common/protobuf.json'
import * as protobuf from 'protobufjs'
import * as pako from 'pako'
import utc from 'dayjs/plugin/utc'
import duration from 'dayjs/plugin/duration'
import { useRouter, useRoute } from 'vue-router'

dayjs.extend(utc)
dayjs.extend(duration)
const route = useRoute()
const router = useRouter()

const internalInstance = getCurrentInstance()

let columns = ref([])
let tableData = ref([])
let total = ref(0)
let pageIndex = ref(1)
let pageSize = ref(2000)
let loading = ref(false)
let TotalData = ref(false)

// 渠道商ID
let ditchIds = ref([])

// 表单查询
let formInline = reactive({
  equipmentId: '957a868',
  user_id: '',
  // updatedAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
})
// 移动的渠道
const equipmentId = ref('')
let room_id_str = ref('7216655694458620687')
// 表单提交
const onSubmit = async () => {
  console.log('submit!', formInline)
  await getDouyinAccountList()
}
columns.value.push(
  ...[
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'equipmentId',
      label: '渠道'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'user_id',
      label: '设备Id'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'name',
      label: '设备名称'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'remarks',
      label: '备注'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'createdAt',
      label: '创建时间'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'updatedAt',
      label: '更新时间'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'operation',
      label: '操作'
    }
  ]
)

/**
 *
 * @returns 获取采集设备列表
 *
 */
async function getDouyinAccountList() {
  loading.value = true
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  let DouYionEquipment = `http://208.87.207.213:38390/CloudUser/DouyinAccountList?equipmentId=${formInline.equipmentId}&sgin=47CFD0A2EB7EA1DC043F1B91926890E9&status=0%2C1%2C-1&page=${pageIndex.value}&pageNo=${pageSize.value}`
  // const SendData = {}
  if (formInline.user_id) {
    DouYionEquipment += `&user_id=${formInline.user_id}`
  }
  const response_ = await fetch(DouYionEquipment, {
    method: 'GET',
    headers: {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: undefined
  })
  let response = await response_.json()
  localStorage.setItem('DouyinAccountList', JSON.stringify(response.data))
  loading.value = false
  console.warn(response.data)
  total.value = response.data.count
  tableData.value = response.data.rows.slice(0, 100)
  TotalData.value = response.data.rows.length
}

onMounted(async () => {
  let DouyinAccountList = localStorage.getItem('DouyinAccountList')
  if (DouyinAccountList) {
    DouyinAccountList = JSON.parse(DouyinAccountList)
    total.value = DouyinAccountList.count
    tableData.value = DouyinAccountList.rows.slice(0, 100)
    TotalData.value = DouyinAccountList.rows.length
  } else {
    await getDouyinAccountList()
  }

  //获取渠道商分组
  let SelectEquiGrouList = `http://208.87.207.213:38390/CloudUser/SelectEquiGrouList?sgin=47CFD0A2EB7EA1DC043F1B91926890E9`
  const response_ = await fetch(SelectEquiGrouList, {
    method: 'GET'
  })
  let response = await response_.json()
  if (response.code == 200 && response.data) {
    let list = response.data || []
    ditchIds.value = list.map((v) => {
      return { value: v.equipmentId || '', label: v.equipmentName || '' }
    })
    localStorage.setItem('ditchIds', JSON.stringify(ditchIds.value))
  }
})
async function handleCurrentChange(number) {
  console.warn('handleCurrentChange', number)
  pageIndex.value = number
  await getDouyinAccountList()
}

const handleSelectionChange = (dataList) => {
  console.warn(dataList)
  CheckDeviceStatus('batch', dataList)
}

let map_wss = ref([])
// 检测设备状态
async function CheckDeviceStatus(item, dataList) {
  let DeviceList = []
  if (item == 'batch') {
    DeviceList = dataList
  } else {
    DeviceList = [item]
  }
  for (let index = 0; index < DeviceList.length; index++) {
    const element = DeviceList[index]
    let login_params = element.login_params
    // 设备对象信息
    let deviceInfo = {}
    // 设备整体数据解析
    let arr = login_params.split('ws_apps=')
    arr[0] = arr[0] + 'ws_apps='
    // 第一段数据截取 包含 mac_addr device_id
    let device_a = arr[0].split('#')
    // 第二段数据截取
    let device_b_arr = arr[1].split('#')
    // 包含手机信息  channel_id app_id mcc_mnc等 类型 对象数组字符串
    let device_c = device_b_arr[0]
    // 包含 device_token= dr_channel cookie
    let device_d = device_b_arr.slice(1, -1)

    // console.warn('device_a--->>', device_a)
    for (const iterator of device_a) {
      let sarr = iterator.split('=')
      deviceInfo[sarr[0]] = sarr[1]
    }
    // console.warn('device_b_arr--->>', device_b_arr)
    // console.warn('device_c--->>', JSON.parse(device_c))
    let jsonc = {}
    try {
      jsonc = JSON.parse(device_c)
    } catch (error) {
      jsonc = JSON.parse(device_c.replaceAll('\\', ''))
    }
    let device_c_extra = device_c ? jsonc[0].extra.split('&') : []
    let extra = {}
    for (const iterator of device_c_extra) {
      let sarr = iterator.split('=')
      extra[sarr[0]] = sarr[1]
    }
    deviceInfo = Object.assign(deviceInfo, device_c ? jsonc[0] : {})
    deviceInfo.extra = extra
    // console.warn('device_d--->>', device_d)
    for (const iterator of device_d) {
      let sarr = iterator.split('=')
      deviceInfo[sarr[0]] = sarr[1]
    }
    console.warn(deviceInfo)
    let newtime = new Date().getTime()
    let channel = deviceInfo['extra']['channel'] || ''
    let device_type = deviceInfo['extra']['device_type'] || ''
    let room_id = room_id_str.value
    let resolution = deviceInfo['extra']['resolution'] || ''
    let cdid = deviceInfo['extra']['cdid'] || ''
    let device_id = deviceInfo['extra']['device_id'] || ''
    let token = ''
    let _rticket = newtime
    let iid = deviceInfo['extra']['iid'] || ''
    let openudid = deviceInfo['extra']['openudid'] || ''
    let sessionId = ''
    let oaid = ''
    let dpi = deviceInfo['extra']['dpi'] || ''
    let device_brand = deviceInfo['extra']['device_brand'] || ''
    let os_version = deviceInfo['extra']['os_version'] || '9'
    let version_name = deviceInfo['extra']['version_name'] || '20.7.0'
    let user_id = '0'
    let version_code = deviceInfo['extra']['version_code'] || '200700'
    let update_version_code = deviceInfo['extra']['update_version_code'] || '20709900'
    let manifest_version_code = deviceInfo['extra']['manifest_version_code'] || '200701'
    let host_abi = deviceInfo['extra']['host_abi'] || 'armeabi-v7a'
    let ts = parseInt(_rticket / 1000)
    let aid = deviceInfo['extra']['aid'] ? parseInt(deviceInfo['extra']['aid']) : 1128
    let access_key = window.api.md5(
      '9e1bd35ec9db7b8d846de66ed140b1ad9' + device_id + 'f8a69f1719916z'
    ) //转换MD5
    let live_room_url = `wss://webcast100-ws-c.amemv.com/webcast/im/push/v2/?is_guest_mode=0&app_type=normal&room_tag=video&channel=${channel}&is_android_pad=0&device_type=${device_type}&language=zh&cpu_support64=true&live_cursor=0&rid=${room_id}&resolution=${resolution}&update_version_code=${update_version_code}&im-sdk-version=2&cdid=${cdid}&minor_status=0&need_persist_msg_count=12&parse_cnt=0&ac=wifi&package=com.ss.android.ugc.aweme&current_network_quality_info=%7B%7D&device_id=${device_id}&compress=gzip&recv_cnt=0&version_code=${version_code}&support_cache=1&im-x-tt-token=${token}&resp_content_type=protobuf&live_id=1&address_book_access=2&user_id=${user_id}&device_platform=android&aid=${aid}&cursor=0&room_id=${room_id}&last_rtt=0&manifest_version_code=${manifest_version_code}&_rticket=${_rticket}&webcast_gps_access=1&iid=${iid}&is_landscape=false&host_abi=${host_abi}&openudid=${openudid}&sid=${sessionId}&is_pad=false&appTheme=light&os_api=28&identity=audience&webcast_locale=zh_CN&dpi=${dpi}&oaid=${oaid}&carrier_region=CN&os=android&os_version=${os_version}&support_wrds=1&webcast_sdk_version=2650&app_name=aweme&version_name=${version_name}&device_brand=${device_brand}&need_personal_recommend=1&webcast_language=zh&ts=${ts}&which_ws=live_ws&version_code=${version_code}&iid=${iid}&platform=0&fpid=9&sdk_version=2&transport_mode=0&device_id=${device_id}&service_id_list=%5B%5D&private_protocol_enable=false&aid=${aid}&ttnet_ignore_offline=1&access_key=${access_key}&ne=1`
    let check_wss = new WebsocketBuild(live_room_url, element.id)
    map_wss.value.push(check_wss)
  }
  // ElMessage({
  //   type: 'success',
  //   message: '检测设备状态成功!'
  // })
}

async function clearCheck() {
  try {
    for (let index = 0; index < map_wss.value.length; index++) {
      await destroyWebSocket(index)
    }
  } catch (error) {
    console.warn(error)
  }
  //   setInterval(() => {
  //   internalInstance.proxy.$forceUpdate()
  // }, 1000)
}

/**
 *
 * @param {*} index
 * 结束一个连接
 */
async function destroyWebSocket(index) {
  if (map_wss.value[index]) {
    let readyState = map_wss.value[index].ws.readyState
    let id = map_wss.value[index].id
    console.warn('readyState', map_wss.value[index].ws.readyState, id)

    map_wss.value[index].destroyWebSocket()
    map_wss.value.splice(index, 1)
    internalInstance.proxy.$forceUpdate()
    if (equipmentId.value) {
      if (readyState == 1) {
        // 回收设备
        await fetch(`http://208.87.207.213:38390/CLoudUser/DouyinAccountUpdate`, {
          method: 'POST',
          headers: {
            'content-type': 'application/json; charset=utf-8'
          },
          body: JSON.stringify({
            id: id,
            equipmentId: equipmentId.value
          })
        })
      }
    }
  }
}

let CommonMessageData = protobufjson.CommonMessageData
let pushproto = protobufjson.pushproto
let RoomDataSyncMessage = protobufjson.RoomDataSyncMessage
let WebcastChatMessage = protobufjson.WebcastChatMessage
let WebcastRoomMessage = protobufjson.WebcastRoomMessage
let WebcastRoomIntroMessage = protobufjson.WebcastRoomIntroMessage
let WebcastGiftMessage = protobufjson.WebcastGiftMessage
let WebcastMemberMessage = protobufjson.WebcastMemberMessage
let WebcastRoomUserSeqMessage = protobufjson.WebcastRoomUserSeqMessage
let WebcastLikeMessage = protobufjson.WebcastLikeMessage
let root = protobuf.Root.fromJSON(pushproto)

class WebsocketBuild {
  // websocket对象
  ws = ''
  // websocket地址
  wsServer = ''
  // 断线重连次数
  limitConnect = 5
  // 累计断线重连次数
  timeConnect = 0
  // websocket binaryType
  binaryType = 'arraybuffer'
  // 定时器
  Interva = null
  // 直播间在线人数
  onlineUserForAnchor = 0
  // 房间聊天信息
  RoomMessage = []
  //url query 参数
  query = {}
  id = ''
  constructor(wsServer, id) {
    this.id = id
    this.wsServer = wsServer
    this.webSocketStart(this.wsServer)
    // 解析url
    let parm_url = new URL(this.wsServer)
    for (const iterator of parm_url.searchParams) {
      this.query[iterator[0]] = iterator[1]
    }
  }
  destroyWebSocket = () => {
    if (this.ws) {
      this.limitConnect = 0
      this.ws.close()
    }
  }
  HeartBeat = () => {
    // 心跳 * 回应
    this.Interva = setInterval(() => {
      if (this.ws) {
        //CONNECTING：值为0，表示正在连接。
        //OPEN：值为1，表示连接成功，可以通信了。
        //CLOSING：值为2，表示连接正在关闭。
        //CLOSED：值为3，表示连接已经关闭，或者打开连接失败。
        if (this.ws.readyState === 1) {
          let Message = root.lookupType('pushproto.PushFrame')
          let message = Message.create({
            payloadType: 'hb'
          })
          let sendada = Message.encode(message).finish()
          this.ws.send(sendada)
          console.warn('发送心跳响应-----')
        }
      }
    }, 5000)
  }
  webSocketStart = () => {
    this.ws = new WebSocket(this.wsServer)
    this.ws.binaryType = 'arraybuffer'
    this.ws.onmessage = this.onmessage
    this.ws.onclose = this.onclose
    this.ws.onopen = this.onopen
  }
  onmessage = (msg) => {
    // console.log('wss服务器消息')
    let messageProto = root.lookup('pushproto.PushFrame')
    let data = msg.data
    let message = null
    try {
      message = messageProto.decode(new Uint8Array(data))
    } catch (error) {
      console.warn(error)
    }
    if (message.headersList.compress_type == 'gzip') {
      // console.warn('解压前----->>>>', message.payload)
      const output = pako.ungzip(message.payload)
      // console.warn('解压后----->>>>', output)
      let unGzipMessage = root.lookup('pushproto.Response')
      let gzipMessage = unGzipMessage.decode(output)
      // this.AnalysisData(gzipMessage.messagesList)
      if (gzipMessage.needAck) {
        let MessageLoad = root.lookupType('pushproto.PushFrame')
        let payload = (function (e) {
          const t = []
          for (const o of e) {
            const e = o.charCodeAt(0)
            e < 128
              ? t.push(e)
              : e < 2048
              ? (t.push(192 + (e >> 6)), t.push(128 + (63 & e)))
              : e < 65536 &&
                (t.push(224 + (e >> 12)), t.push(128 + ((e >> 6) & 63)), t.push(128 + (63 & e)))
          }
          return Uint8Array.from(t)
        })(gzipMessage.internalExt)
        // let message_res = MessageLoad.create({ payloadType: "ack", payload: payload, logid: message.logid });
        let headersList = []
        for (const key in message.headersList) {
          const element = message.headersList[key]
          headersList.push({
            [message.headersList[key]]: element
          })
        }
        let message_res = MessageLoad.create({
          payloadType: 'ack',
          payload: payload,
          logid: message.logid,
          headersList
        })
        let sendada = MessageLoad.encode(message_res).finish()
        this.ws.send(sendada)
        // console.warn('发送ACK响应-----')
      }
    }
  }
  // 数据解析
  AnalysisData = (data) => {
    try {
      let messagesList = data
      for (const iterator of messagesList) {
        // console.warn(iterator.method)
        let info = {}
        switch (iterator.method) {
          case 'WebcastRoomDataSyncMessage':
            let RoomDataSyncResult = protobuf.Root.fromJSON(RoomDataSyncMessage)
            let room_data_sync_message = RoomDataSyncResult.lookup('RoomDataSyncMessage')
            let RoomDataSyncData = room_data_sync_message.decode(iterator.payload)
            info = RoomDataSyncData.toJSON()
            // console.warn(info)
            if (info.user) {
              let msg = `${info.user.nickname} (${info.user.id})&sec_user_id=${info.user.secUid}`
              this.RoomMessage.push(msg)
            }
            break
          case 'WebcastChatMessage':
            let ChatMessageResult = protobuf.Root.fromJSON(WebcastChatMessage)
            let ChatMessage = ChatMessageResult.lookup('ChatMessages')
            let ChatMessageData = ChatMessage.decode(iterator.payload)
            // console.warn(ChatMessageData.toJSON())
            info = ChatMessageData.toJSON()
            let msg = `${info.user.nickname} (${info.user.id}):${info.content}&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg)
            break
          case 'WebcastRoomMessage':
            let WebcastRoomResult = protobuf.Root.fromJSON(WebcastRoomMessage)
            let webcast_roomMessage = WebcastRoomResult.lookup('WebcastRoomMessage')
            let MessageData = webcast_roomMessage.decode(iterator.payload)
            // console.warn(MessageData.toJSON())
            info = MessageData.toJSON()
            let msg2 = `${info.user.nickname} (${info.user.id}):进入直播间&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg2)
            break
          case 'WebcastRoomIntroMessage':
            let RoomIntroResult = protobuf.Root.fromJSON(WebcastRoomIntroMessage)
            let RoomIntroMessageData = RoomIntroResult.lookup('RoomIntro.RoomIntroMessage')
            let RoomIntroData = RoomIntroMessageData.decode(iterator.payload)
            // console.warn(RoomIntroData.toJSON())
            info = RoomIntroData.toJSON()
            let msg3 = ` ${info.user.nickname} (${info.user.id}):&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg3)
            break
          case 'WebcastGiftMessage':
            let GiftMessageResult = protobuf.Root.fromJSON(WebcastGiftMessage)
            let GiftMessageMessageData = GiftMessageResult.lookup('dy.GiftMessage')
            let GiftMessageData = GiftMessageMessageData.decode(iterator.payload)
            // console.warn(GiftMessageData.toJSON())
            info = GiftMessageData.toJSON()
            let msg4 = `${info.user.nickname} (${info.user.id}):送礼物&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg4)
            break
          case 'WebcastMemberMessage':
            let MemberMessageResult = protobuf.Root.fromJSON(WebcastMemberMessage)
            let MemberMessageData = MemberMessageResult.lookup('MemberMessage')
            let MemberData = MemberMessageData.decode(iterator.payload)
            // console.warn(MemberData.toJSON())
            info = MemberData.toJSON()
            let msg5 = `${info.user.nickname} (${info.user.id}):来了&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg5)
            break
          case 'WebcastLikeMessage':
            let LikeMessageResult = protobuf.Root.fromJSON(WebcastLikeMessage)
            let LikeMessageData = LikeMessageResult.lookup('LikeMessage')
            let LikeData = LikeMessageData.decode(iterator.payload)
            // console.warn(LikeData.toJSON())
            info = LikeData.toJSON()
            let msg6 = `${info.user.nickname} (${info.user.id}):点赞&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg6)
            break
          case 'WebcastRoomUserSeqMessage':
            let RoomUserSeqResult = protobuf.Root.fromJSON(WebcastRoomUserSeqMessage)
            let SeqMessageData = RoomUserSeqResult.lookup('RoomUserSeqMessage')
            let SeqData = SeqMessageData.decode(iterator.payload)
            // console.warn(SeqData.toJSON())
            info = SeqData.toJSON()
            // 当前直播间人数
            if (info.onlineUserForAnchor) {
              this.onlineUserForAnchor = info.onlineUserForAnchor
              onlineUserForAnchor.value = info.onlineUserForAnchor
              console.warn('当前直播间人数---->>>', this.onlineUserForAnchor)
            }
            break
          default:
            break
        }
      }
    } catch (error) {}
  }
  onclose = () => {
    console.log('wss服务器已经断开')
    this.reconnect(this.wsServer)
  }
  onopen = () => {
    console.log('已连接wss服务器')
    this.HeartBeat()
  }
  reconnect = () => {
    // lockReconnect加锁，防止onclose、onerror两次重连
    if (this.limitConnect > 0) {
      this.limitConnect--
      this.timeConnect++
      // console.log('第' + this.timeConnect + '次重连')
      // 进行重连
      setTimeout(() => {
        this.webSocketStart(this.wsServer)
      }, 2000)
    } else {
      // console.log('wss连接已超时')
    }
  }
}
const Logout = async () => {
  localStorage.removeItem('userinfo')
  localStorage.removeItem('DouYinTaskList')
  router.push({
    path: '/Login',
    query: {
      ...route.query
    }
  })
}
// 设备检测
const checkDevice = async () => {
  electron.ipcRenderer.send('start_schedule', true)
}
</script>

<template>
  <div class="container no-drag">
    <div class="tablebox" style="overflow: auto; margin-bottom: 10px">
      <el-button size="small" type="primary" @click="Logout">退出登录</el-button>
      <el-button size="small" type="primary" @click="checkDevice">开启自动检测</el-button>
      <div>
        设备检测列表:{{ map_wss.length
        }}<el-input
          v-model="room_id_str"
          style="width: 200px; margin-left: 20px"
          placeholder="输入检测的房间号"
        ></el-input>
      </div>
      <table border="1" cellspacing="0" cellpadding="0" style="width: 100%; margin-top: 10px">
        <thead>
          <tr>
            <th>房间号</th>
            <th>设备号</th>
            <th>wss连接状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody v-if="map_wss.length > 0">
          <tr v-for="(item, index) in map_wss" :key="index" style="text-align: center">
            <td>{{ item.query['room_id'] }}</td>
            <td>{{ item.query['device_id'] }}</td>
            <td>{{ ['正在连接', '连接成功', '连接关闭', '连接失败'][item.ws.readyState] }}</td>
            <td>
              <div>
                <el-button type="danger" size="small" @click="destroyWebSocket(index)">{{
                  item.readyState != 1 ? '移除连接' : '销毁连接'
                }}</el-button>
              </div>
            </td>
          </tr>
        </tbody>
        <tbody style="display: flex; justify-content: center; align-items: center" v-else>
          暂无数据
        </tbody>
      </table>
    </div>
    <div class="search">
      <el-form ref="queryForm" :inline="true" :model="formInline">
        <el-form-item label="渠道id：">
          <el-select v-model="formInline.equipmentId" class="m-2" placeholder="请选择渠道商">
            <el-option
              v-for="(item, index) in ditchIds"
              :key="index"
              :label="item.label + '--' + item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备id：">
          <el-input v-model="formInline.user_id" placeholder="请输入设备id" />
        </el-form-item>
        <el-form-item label="设备创建时间：">
          <el-input
            v-model="formInline.createdAt"
            :value="formInline.createdAt"
            type="datetime-local"
            placeholder="请选择时间"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="设备更新时间：">
            <el-input
              v-model="formInline.updatedAt"
              :value="formInline.updatedAt"
              type="datetime-local"
              placeholder="请选择时间"
            ></el-input>
          </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="clearCheck">清除当前检测列表</el-button>
        </el-form-item>
        <el-form-item label="渠道id：">
          <el-select v-model="equipmentId" class="m-2" placeholder="请选择目标渠道商">
            <el-option
              v-for="(item, index) in ditchIds"
              :key="index"
              :label="item.label + '--' + item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      empty-text="暂无数据"
      border
      stripe
      row-key="id"
      size="large"
      style="width: 100%"
      height="500"
      highlight-current-row
      :header-cell-style="{ background: '#F9F9F9', color: '#606266' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align"
        :show-overflow-tooltip="true"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
      >
        <template #default="scope">
          <div v-if="item.prop == 'operation'">
            <el-button size="small" type="primary" @click="CheckDeviceStatus(scope.row)"
              >添加检测设备</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-button style="margin-top: 10px" type="primary" size="small" @click="getDouyinAccountList"
      >更新设备列表</el-button
    >

    <div style="color: red">
      注意：开始任务获取的设备默认第一页;默认一次获取{{ pageSize }}设备数量
      <span style="margin-top: 10px">可输入获取的设备数：</span>
      <el-input-number v-model="pageSize"></el-input-number>
    </div>
    <!-- 合计统计显示 -->
    <div class="total_tatistics">
      <span>总设备数：{{ total || '0' }} </span>
      <span style="margin-left: 10px">当前页获取设备数量：{{ TotalData || '0' }} </span>
      <span style="margin-left: 10px">当页展示设备数：{{ tableData.length || '0' }} </span>
    </div>
    <div class="pagination">
      <el-pagination
        :current-page="pageIndex"
        layout=" prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        background
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="less">
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.total_tatistics {
  padding: 12px;
  font-family: auto;
  font-size: 15px;
  font-weight: bold;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 19px;
}
</style>
